package com.hiyori.hiyorinovel;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String URL = "jdbc:mysql://localhost:3306/novaldata?useSSL=false&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "Hiyori";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try {
            // 使用SHA-256对输入的密码进行哈希加密
            String hashedPassword = hashPassword(password);
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }

            try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
                // 查询账户和哈希密码的 SQL 语句
                String query = "SELECT UID, nickname, email FROM userdata WHERE username = ? AND password = ?";
                try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
                    preparedStatement.setString(1, username);
                    preparedStatement.setString(2, hashedPassword);
                    try (ResultSet resultSet = preparedStatement.executeQuery()) {
                        if (resultSet.next()) {
                            // 如果账户和密码正确
                            String Uid = resultSet.getString("UID");
                            String nickname = resultSet.getString("nickname");
                            String email = resultSet.getString("email");

                            // 保存到 session
                            HttpSession session = request.getSession();
                            session.setAttribute("UID", Uid);
                            session.setAttribute("username", username);
                            session.setAttribute("nickname", nickname);
                            session.setAttribute("email", email);

                            // 重定向到信息页面
                            response.sendRedirect("../info/loginend.jsp");
                        } else {
                            // 如果账户或密码不正确
                            response.sendRedirect("../info/loginend.jsp?error=Invalid username or password");
                        }
                    }
                }
            }
        } catch (SQLException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            response.sendRedirect("../info/loginend.jsp?error=Database connection error");
        }
    }

    private String hashPassword(String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashedBytes = md.digest(password.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : hashedBytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}